import React, { useEffect, useState } from 'react';
import { history } from 'umi';
import { Result, Spin } from 'antd';
import { PermissionUtils } from '@/utils/permission';

interface RouteGuardProps {
    children: React.ReactNode;
    path: string;
}

const RouteGuard: React.FC<RouteGuardProps> = ({ children, path }) => {
    const [loading, setLoading] = useState(true);
    const [hasPermission, setHasPermission] = useState(false);

    useEffect(() => {
        checkPermission();
    }, [path]);

    const checkPermission = () => {
        const permission = PermissionUtils.hasPathPermission(path);
        setHasPermission(permission);
        setLoading(false);
    };

    if (loading) {
        return (
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
                <Spin size="large" />
            </div>
        );
    }

    if (!hasPermission) {
        return (
            <Result
                status="403"
                title="403"
                subTitle="抱歉，您没有权限访问此页面"
                extra={
                    <button
                        onClick={() => history.push('/home')}
                        style={{
                            background: '#1890ff',
                            color: 'white',
                            border: 'none',
                            padding: '8px 16px',
                            borderRadius: '4px',
                            cursor: 'pointer'
                        }}
                    >
                        返回首页
                    </button>
                }
            />
        );
    }

    return <>{children}</>;
};

export default RouteGuard;